<template>
  <div class="create-post-page container">
    <h4>新建文章</h4>
    <m-form :rules="rules" class="form" :model="model" ref="formRef">
      <m-form-item prop="title" label="文章标题">
        <m-input
          type="text"
          placeholder="请输入与文章标题"
          v-model="model.title"
        />
      </m-form-item>
      <m-form-item prop="content" label="文章详情">
        <m-input
          type="textarea"
          placeholder="请输入文章详情"
          v-model="model.content"
        />
      </m-form-item>
      <m-form-item
        ><button
          @click.prevent="submitForm"
          class="btn btn-primary btn-block btn-large"
        >
          发表文章
        </button>
      </m-form-item>
    </m-form>
  </div>
</template>

<script>
import MForm from '@/components/MForm';
import MFormItem from '@/components/MForm/MFormItem';
import MInput from '@/components/MForm/MInput';
import { reactive, ref } from 'vue';
import { createPosts } from '@/api/post';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
export default {
  name: 'Article',
  components: {
    MForm,
    MFormItem,
    MInput,
  },
  setup() {
    const rules = {
      title: [{ required: true, message: '文章标题不能为空', trigger: 'blur' }],
      content: [
        { required: true, message: '文章详情不能为空', trigger: 'blur' },
      ],
    };
    const formRef = ref();
    const store = useStore();
    const router = useRouter();
    const model = reactive({
      title: '',
      content: '',
    });

    const submitForm = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          _createPost();
        } else {
          return false;
        }
      });
    };

    const _createPost = async () => {
      const author = store.getters.id;
      let column = store.getters.column;
      let params = { ...{}, ...model, author, column };
      const res = await createPosts(params);
      model.title = '';
      model.content = '';
      // 跳转专栏列表
      router.push({ name: 'Column', params: { id: res.column } });
    };

    return {
      rules,
      model,
      formRef,
      submitForm,
    };
  },
};
</script>

<style lang="scss" scoped></style>
